import "./App.css";
import { useState, useCallback, useEffect } from "react";
import crypto from "crypto";
const categoryList = [
  "社会生活",
  "军事",
  "政治",
  "医药健康",
  "文体娱乐",
  "财经商业",
  "教育考试",
  "科技",
  "灾难事故",
  "无法确定",
];
let fileMd5 = "";
let fileName = "";
let finished = 0;
function App() {
  const [inited, setInited] = useState(false);
  const [loading, setLoading] = useState("拖入JSON文件");
  const [sourceData, setSourceData] = useState([]);
  const [lastModify, setLastModify] = useState();
  const fileHandler = useCallback((e) => {
    e.preventDefault();
    setInited(false);
    setLoading("获取文件Hash...");

    if (e.dataTransfer.files?.length) {
      const fileSource = e.dataTransfer.files[0];
      const fileReader = new FileReader();
      fileReader.readAsText(fileSource);
      fileReader.onload = () => {
        try {
          fileMd5 = crypto
            .createHash("md5")
            .update(fileSource.name)
            .digest("hex");
          fileName = fileSource.name.split(".")[0];
          const data = JSON.parse(fileReader.result);
          console.log("JSON已读取");
          setLoading("读取文件...");

          setTimeout(() => {
            const resultSet = new Set();
            const result = [];
            while (data.length > 0) {
              const target = data.shift();
              if (!resultSet.has(target.id)) {
                resultSet.add(target.id);
                result.push(target);
              }
            }
            let lastData = null;
            setSourceData(
              result.map((item) => {
                const id = fileMd5 + item.id;
                const category = item.category || localStorage.getItem(id);
                if (category) {
                  finished++;
                } else if (!lastData) {
                  lastData = item.id;
                }
                return {
                  ...item,
                  category,
                };
              })
            );
            setLastModify(lastData);
            setInited(true);
            setLoading("");
          });
        } catch (e) {
          console.error(e);
        }
      };
    }
  }, []);
  useEffect(() => {
    if (lastModify) {
      requestAnimationFrame(() => {
        const target = document.getElementById(lastModify);
        target.scrollIntoView({ behavior: "smooth" });
      });
    }
  }, [lastModify]);
  const exportData = useCallback(() => {
    const string = JSON.stringify(sourceData);
    const blob = new Blob([string]);
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    const time = new Date();
    link.download = `${time.getFullYear()}-${
      time.getMonth() + 1
    }-${time.getDate()}-${fileName}-resolve-${finished}.json`;
    link.href = url;
    link.click();
  }, [sourceData]);
  return (
    <div
      className="App"
      style={
        inited
          ? { border: "0", background: "#fff" }
          : { border: "2px dashed #000", background: "rgba(0,0,0,0.05)" }
      }
      onDragOver={(e) => {
        e.preventDefault();
      }}
      onDrop={fileHandler}
    >
      {!inited && <div className="input">{loading}</div>}
      {inited && (
        <div className="data-view" id="dataView">
          <div className="download" onClick={exportData} id={"export"}>
            导出数据 ({finished}/{sourceData.length})
          </div>
          {sourceData.map((item, index) => {
            return (
              <div
                className="item-cover"
                key={item.id}
                id={item.id}
                style={{ color: item.category ? "#aaa" : "" }}
              >
                <div className="title">
                  {index + 1} {item.content}
                </div>
                <div className="select">
                  {categoryList.map((tag) => (
                    <label key={tag}>
                      <input
                        type="radio"
                        name={item.id}
                        defaultChecked={tag === item.category}
                        onChange={(e) => {
                          const node =
                            e.target.parentElement.parentElement.parentElement;
                          if (!item.category) {
                            document.getElementById(
                              "export"
                            ).innerText = `导出数据 (${++finished}/${
                              sourceData.length
                            })`;
                            if (index % 2 === 1)
                              node.scrollIntoView({ behavior: "smooth" });
                          }
                          item.category = tag;
                          localStorage.setItem(fileMd5 + item.id, tag);

                          node.style.color = "#aaa";
                        }}
                      ></input>
                      {tag}
                    </label>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

export default App;
